﻿using Cofe.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cofe.IO
{
    public static class DirectoryFE
    {
        public static Task<IDirectoryInfo> FromDirectoryPathAsync(string fullParsePath, 
            EntryConstructionFlags flags = EntryConstructionFlags.DefaultWithLookup)
        {
            return EntryFE.TryParsePathAsync<IDirectoryInfo>(fullParsePath, ParsableType.ParsePath, flags);
        }


        public static async Task<IDirectoryInfo> CreateDirectoryAsync(string path)
        {
            string[] pathSplit = path.Split(new char[] { '\\' });

            int idx = 0;
            string curPath = null;
            string lastPath = "";
            
            
            //Continue the loop if directory is exists, because they dont need to be created.
            while (idx < pathSplit.Length && (curPath == null || EntryFE.Exists(curPath)))
            {
                lastPath = curPath;
                string curFragment = pathSplit[idx++];
                curPath = curPath != null ? PathFE.Combine(curPath, curFragment) : curFragment;
                if (curPath.EndsWith(":")) curPath += "\\";
            }

            if (EntryFE.Exists(curPath))
                lastPath = curPath;
            else idx--;

            //If lastPath is not set at all, even root directory is not found.
            if (String.IsNullOrEmpty(lastPath))
                throw new System.IO.FileNotFoundException("Root not found.");

            IDirectoryInfo lastDir = await EntryFE.TryParsePathUncachedAsync<IDirectoryInfo>(lastPath);

            //If lastDir cannot be parsed as IDirectoryInfo, throw exception.
            if (lastDir == null)
                throw new ArgumentException(lastPath + " is not a directory.");

            //Forward directory construction.
            for (int i = idx; i < pathSplit.Length; i++)            
                lastDir = await lastDir.CreateDirectoryAsync(pathSplit[i]);            

            return lastDir;
        }

        public static async Task DeleteAsync(string dirPath, bool raiseAlert)
        {
            IDirectoryInfo dir = await EntryFE.TryParsePathUncachedAsync<IDirectoryInfo>(dirPath);
            if (dir is IDirectoryInfo)
                await dir.DeleteAsync();
            else throw new System.IO.FileNotFoundException(dirPath + " not found.");
        }

        public static bool Exists(string folderPath)
        {
            IDirectoryInfo foundDirectory = (EntryFE.TryParsePathUncachedAsync<IDirectoryInfo>(folderPath)).Result;
            return foundDirectory != null;
        }


    }
}
